package com.gang.ssm.bos.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gang.ssm.bos.common.TreeNode;
import com.gang.ssm.bos.core.anotation.Permission;
import com.gang.ssm.bos.core.toolbox.ajax.AjaxResult;
import com.gang.ssm.bos.system.bean.Menu;
import com.gang.ssm.bos.system.service.MenuService;

@RequestMapping("/menu")
@Controller
public class MenuController extends BosController {
	
	@Autowired
	private MenuService menuService;
	
	@RequestMapping("/list")
	public String list(Map<String, Object> map) {

		try {

			map.put("menuList", menuService.findForTreeTable(0));
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "system/menu/menuList";
	}

	/**
	 * 查询下级菜单
	 * 
	 * @param parentId
	 * @return
	 */
	@RequestMapping("/treeTable")
	@ResponseBody
	public AjaxResult treeTable(Integer parentId) {

		List<Menu> menuList = null;
		try {
			menuList = menuService.findForTreeTable(parentId);
			return success(menuList);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fail("读取菜单出错!");
	}

	/**
	 * 维护页面跳转
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/menu")
	public String menu(Integer id, Map<String, Object> map) {

		try {

			if (id != null) {
				map.put("menu", menuService.getById(id));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "system/menu/menu";
	}

	/**
	 * 获取菜单树状结构
	 * 
	 * @return
	 */
	@RequestMapping("/getMenuForTree")
	@ResponseBody
	public AjaxResult getMenuForTree() {

		List<Menu> menuList = menuService.find(new Menu());

		List<TreeNode> nodes = new ArrayList<TreeNode>();
		if (menuList != null && menuList.size() > 0) {
			TreeNode node = null;
			for (Menu menu : menuList) {
				node = new TreeNode();
				node.setId(menu.getId());
				node.setName(menu.getMenuName());
				node.setpId(menu.getParentId());
				
				nodes.add(node);
			}
		}

		return success(nodes);
	}

	/**
	 * 保存数据
	 * 
	 * @param menu
	 * @return
	 */
	@Permission({ADMIN})
	@RequestMapping("/save")
	@ResponseBody
	public AjaxResult save(Menu menu) {

		try {
			
			menuService.saveOrUpdate(menu);
			return success("保存成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fail("保存失败!");
	}

	/**
	 * 删除数据
	 * 
	 * @param id
	 * @return
	 */
	@Permission({ADMIN})
	@RequestMapping("/delete")
	@ResponseBody
	public AjaxResult delete(Integer id) {

		try {

			menuService.deleteById(id);
			return success("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return fail("删除失败!");
	}

}
